import { Button, Card, Col, Form, Input, message, Row, Table } from 'antd';
import '../interview/index.scss';
import { getInterviewInfo } from '@/apis/interview'
import { forwardRef, useEffect, useImperativeHandle, useState } from 'react';
import type { InterviewInfoDto, InterviewInfoVo } from '@/types';
import { FormOutlined, SearchOutlined } from '@ant-design/icons';

const Interview = forwardRef((props, ref) => {
    /** 
     * 更改查询条件回调 
     * 调用时机
     * 1.修改当前页数和每页显示条数时
     * 2.查询条件表单的条件修改
     */
    const changeSeleteCondition = (params: InterviewInfoDto) => {
        console.log("changeSeleteCondition========>",params);
        setQueryForm(params);   
    }

    /** 查询  */
    const queryInterviewInfo = async () => {
        setLoading(true);
        const res = await getInterviewInfo(queryForm);
        console.log("面试信息=======>",res.data.records);
        // 获取数据为空 且 当前页数不为1时，将当前页数-1再查一遍
        /**
         * 解决：
         *  1.在删除第二页最后一条数据后，重新查询时当前页数还是2，解决后：查不到之后，会-1变成1
         *  2.当前在第二页，然后搜索存在的数据的条件，若存在的数据不满足2页，则会显示为空 解决后：查不到之后，会-1变成1
         */
        if (res.data.records.length === 0 && queryForm.current !== 1) {
            setQueryForm({
                ...queryForm,
                current: queryForm.current - 1
            })
            return;
        }
        setTableData(res.data.records);
        setTotal(res.data.total);
        setLoading(false);
    }

    /** 重置  */
    const reset = () => {
        form.resetFields();
        setQueryForm({
            current: 1,
            size: 6
        })
        setSelectDataIds([]);
        setSelectDatas([]);
        // todo 清空表格选中的数据项
    }

    /** 暴露给外部组件获取选中的数据回调  */
    const handleReturn = async () => {
        if (selectedDatas.length === 0) {
            message.warning('请选择数据后再进行操作！');
            return [];
        }
        return selectedDatas;
    }   

    /** 表格选中回调  */
    const tabSelectChange = (selectedRowKeys: React.Key[], selectedRows: InterviewInfoVo[]) => {
        setSelectDataIds(selectedRowKeys as string[]);
        setSelectDatas(selectedRows as InterviewInfoVo[]);
        console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    }
    // 表单标识
    const [form] = Form.useForm();
    // 表格数据
    const [tableData,setTableData]  = useState<InterviewInfoVo[]>([]);
    // 总记录数
    const [total,setTotal] = useState(0);
    // 查询条件
    const [queryForm,setQueryForm] = useState<InterviewInfoDto>({
        current: 1,
        size: 6
    })
    // 加载中标识
    const [loading, setLoading] = useState(false);
    // 当前选中的数据行id
    const [selectDataIds,setSelectDataIds] = useState<string[]>([]);
    // 当前选中的数据
    const [selectedDatas,setSelectDatas] = useState<InterviewInfoVo[]>([]);    

    useEffect(() => {
        queryInterviewInfo();
    }, [queryForm]); // 当 queryForm 的值变化时才触发

    const columns = [
        {
            title: '面试标题',
            dataIndex: 'title',
        },
        {
            title: '候选人',
            dataIndex: 'candidateName',
        },
        {
            title: '面试官',
            dataIndex: 'interviewersName',
        },
        {
            title: '操作',
            dataIndex: 'action',
            render: (value: string, record:InterviewInfoVo) => (
                <>
                    <Row gutter={16}>
                        <Col>
                            <Button onClick={() => console.log("record=====>",record)} color='primary' variant="outlined" icon={<FormOutlined />}/>
                        </Col>
                    </Row>
                </>
            ),
        }
    ];

    useImperativeHandle(ref, () => ({
        handleReturn: handleReturn,
        reset: reset
    }));

    return (
        <div className='interview-container'>
            <Card title='查询条件' style={{ borderRadius: 0 }}>
                <Form
                    form={form}
                    layout="inline"
                    name="interviewInfo"
                    labelCol={{ span: 8 }}
                    wrapperCol={{ span: 16 }}
                    style={{ width: '100%' }}
                    initialValues={{ }}
                    onFinish={(val) => { changeSeleteCondition({...queryForm,...val}) }}
                    autoComplete="off"
                >
                    <Row style={{ width: '100%' }}>
                        <Form.Item<InterviewInfoDto>
                            label="面试标题"
                            name="title"
                        >
                            <Input />
                        </Form.Item>

                        <Form.Item<InterviewInfoDto>
                            label="候选人名称"
                            name="candidateName"
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item<InterviewInfoDto>
                            label="面试官名称"
                            name="interviewerName"
                        >
                            <Input />
                        </Form.Item>
                    </Row>

                    <Row justify="end" style={{ width: '100%',marginTop: '20px' }}>
                        <Form.Item label={null}>
                            <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                                查询
                            </Button>
                        </Form.Item>
                    </Row>
                </Form>
            </Card>

            <Card title='查询结果' style={{ marginTop: '20px',borderRadius: 0 }}>
                <Table
                    rowKey="id" 
                    loading={loading}
                    pagination={{ 
                        position: ['bottomRight'],
                        current: queryForm.current,
                        pageSize: queryForm.size,
                        total: total,
                        onChange: (current, size) => changeSeleteCondition({...form.getFieldsValue(),current,size}),
                        showTotal: (total) => `共 ${total} 条数据`,
                        showSizeChanger: true,
                        pageSizeOptions: [6,10,20,50,100]
                    }}
                    rowSelection={{ type: 'checkbox',onChange: tabSelectChange,selectedRowKeys: selectDataIds,preserveSelectedRowKeys: true }} 
                    dataSource={tableData} 
                    columns={columns} 
                />
            </Card>
        </div>
    )
})

export default Interview;